import * as React from 'react';
import FormControl from 'react-bootstrap/es/FormControl';
import HelpBlock from "react-bootstrap/es/HelpBlock";
export default class ValidatedInput extends React.PureComponent<any, any>{

  private _registerInput;
  private _unregisterInput;
  private inputProps;
  constructor(props) {
    super(props);

    const { _registerInput, _unregisterInput } = props;
    this._registerInput = _registerInput;
    this._unregisterInput = _unregisterInput;  
    if (!this._registerInput || !this._unregisterInput) {
      throw new Error('Input must be placed inside the Form component');
    }
  }

  componentWillMount() {
    this._registerInput(this);
  }

  componentWillUnmount() {
    this._unregisterInput(this);
  }

  render() {
    const {
      help,
      success,
      successHelp,
      validationEvent,
      validate,
      validating,
      validatingHelp,
      errorHelp,
      _registerInput,
      _unregisterInput,
      ...props } = this.props;
    return (
      <div>
        <FormControl ref='control' {...props}>{this.props.children}</FormControl>
        {help && <HelpBlock>{help}</HelpBlock>}
        {validating && <HelpBlock>{validatingHelp}</HelpBlock>}
        {success && <HelpBlock>{successHelp}</HelpBlock>}
      </div>
    )
  }


  static propTypes = {
    name: React.PropTypes.string.isRequired,
    validationEvent: React.PropTypes.oneOf([
      '', 'onChange', 'onBlur', 'onFocus'
    ]),

    validatingHelp: React.PropTypes.oneOfType([
      React.PropTypes.string, React.PropTypes.object
    ]),
    validate: React.PropTypes.oneOfType([
      React.PropTypes.func,
      React.PropTypes.string
    ]),
    success: React.PropTypes.bool,
    errorHelp: React.PropTypes.oneOfType([
      React.PropTypes.string,
      React.PropTypes.object
    ])
  };

  static defaultProps = {
    validationEvent: '',
    validating: false,
  };
}

